import { Component, Vue, Model } from 'vue-property-decorator';

/**
 * 定义当前数据
 */
interface Validate {
    loginAccount: string;
    password: string;
}

/**
 * 定义当前表单验证
 */
interface validatePassFunc {
    loginAccount: {
        required: true,
        trigger: string,
        validator: (rule: any, value: string, callback: () => {}) => void,
    };
    password: {
        required: true,
        trigger: string
        validator: (rule: any, value: string, callback: () => {}) => void,
    }
}

@Component({
    name: 'login',
})

export default class Login extends Vue {
    // 定义input type
    private ruleForm: Validate = {
        loginAccount: '',
        password: ''
    }

    // 表单验证
    private loginRules: validatePassFunc = {
        loginAccount: {
            required: true,
            trigger: 'change',
            validator: (rule: any, value: string, callback: (res?: any) => {}) => {
                if (value === '') {
                    callback(new Error('请输入用户名'))
                } else {
                    callback()
                }
            },
        },
        password: {
            required: true,
            trigger: 'change',
            validator: (rule: any, value: string, callback: (res?: any) => {}) => {
                if (value.length < 5) {
                    callback(new Error('密码不能小于5位'));
                } else {
                    callback();
                }
            },
        }
    }


    submitForm(formName: string): void {
        if (this.Verification()) {
            this.$message({
                showClose: true,
                message: '登陆成功',
                type: 'success',
                onClose:()=>{
                    this.$router.replace('/index')
                }
            })
        }
        // (this.$refs[formName] as HTMLFormElement).validate((valid: any) => {})
    }

    /**
     * 表单验证
     */
    Verification(): boolean {
        // 账号的验证
        if (!this.account(this.ruleForm.loginAccount).status) {
            this.$message(this.account(this.ruleForm.loginAccount).msg);
            return false;
        }
        // 密码的验证
        if (!this.password(this.ruleForm.password).status) {
            this.$message(this.password(this.ruleForm.password).msg);
            return false;
        }
        return true;
    }

    /**
     * 表单的账号非空验证
     * @param item 账号验证
     */
    account(item: string): any {
        if (item === '' || item === null) {
            return { status: false, msg: '请填写账号' };
        }
        return { status: true };
    }

    /**
     * 表单密码的验证
     * @param item 密码的表单验证
     */
    password(item: string): any {
        const regular: any = /^(?!([a-zA-Z]+|\d+)$)[a-zA-Z\d]{6,20}$/;
        if (item === '' || item === null) {
            return { status: false, msg: '请填写密码' };
        }
        if (item.length < 6) {
            return { status: false, msg: '密码不能小于5位' };
        }
        return { status: true };
    }

}
